package com.fzhucc.modules.lesson.service.impl;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.lesson.domain.Lesson;
import com.fzhucc.modules.lesson.domain.LessonRecord;
import com.fzhucc.modules.lesson.domain.dto.LessonIntegralQueryCriteria;
import com.fzhucc.modules.lesson.domain.dto.LessonQueryCriteria;
import com.fzhucc.modules.lesson.domain.dto.LessonRecordDto;
import com.fzhucc.modules.lesson.domain.dto.LessonRecordQueryCriteria;
import com.fzhucc.modules.lesson.repository.LessonRecordRepository;
import com.fzhucc.modules.lesson.repository.LessonRepository;
import com.fzhucc.modules.lesson.service.LessonRecordService;
import com.fzhucc.modules.lesson.service.mapstruct.LessonRecordMapper;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.UserService;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* @description 服务实现
* @author yyg
* @date 2022-12-07
**/
@Service
@RequiredArgsConstructor
public class LessonRecordServiceImpl implements LessonRecordService {

    private final LessonRecordRepository lessonRecordRepository;
    private final LessonRecordMapper lessonRecordMapper;
    private final UserService userService;
    private final LessonRepository lessonRepository;

    private final UserRepository userRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Override
    public Map<String,Object> queryAll(LessonRecordQueryCriteria criteria, Pageable pageable){
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        Page<LessonRecord> page = lessonRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<LessonRecordDto> res = page.map(lessonRecordMapper::toDto);
        List<LessonRecordDto> list = res.getContent();
        for (LessonRecordDto lessonRecordDto : list) {
            lessonRecordDto.setUserDto(userService.findById(lessonRecordDto.getUserId()));
            Optional<Lesson> result = lessonRepository.findById(lessonRecordDto.getLessonId());
            if (result.isPresent()){
                lessonRecordDto.setLesson(result.get());
            }
        }
        return PageUtil.toPage(res);
    }

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(LessonRecordQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                //不赋予则返回所有都能看
                return null;
            }
            if (res.getOrgArea().contains(";")) {
                String[] split = res.getOrgArea().split(";");
                if (split.length == 2) {
                    return split[1];
                } else if (split.length == 3) {
                    return split[1];
                } else if (split.length == 1) {
                    return split[0];
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            } else {
                throw new BadRequestException("未符合规范的地区区域");
            }
        }
    }

    @Override
    public List<LessonRecordDto> queryAll(LessonRecordQueryCriteria criteria){
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        return lessonRecordMapper.toDto(lessonRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public LessonRecordDto findById(Integer id) {
        LessonRecord lessonRecord = lessonRecordRepository.findById(id).orElseGet(LessonRecord::new);
        ValidationUtil.isNull(lessonRecord.getId(),"LessonRecord","id",id);
        return lessonRecordMapper.toDto(lessonRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LessonRecordDto create(LessonRecord resources) {
        resources.setOrgArea(orgAreaReturn());
        return lessonRecordMapper.toDto(lessonRecordRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(LessonRecord resources) {
        LessonRecord lessonRecord = lessonRecordRepository.findById(resources.getId()).orElseGet(LessonRecord::new);
        ValidationUtil.isNull( lessonRecord.getId(),"LessonRecord","id",resources.getId());
        lessonRecord.copy(resources);
        lessonRecord.setOrgArea(orgAreaReturn());
        lessonRecordRepository.save(lessonRecord);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            lessonRecordRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<LessonRecordDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (LessonRecordDto lessonRecord : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("课程id", lessonRecord.getLessonId());
            map.put("userid", lessonRecord.getUserId());
            map.put("购买时间", lessonRecord.getBuyTime());
            map.put("区域划分", lessonRecord.getBuyTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}